import base64
import os
from configparser import ConfigParser

from Crypto.Random import get_random_bytes

from commons.crypt import Crypt


def translate():
    """
    对设置文件加密
    :return:
    """
    origin = os.environ.get('origin_path')
    target = os.environ.get('config_path')
    kp = os.environ.get('key')

    key = get_random_bytes(16)
    c = Crypt(base64.b64encode(key))

    parser = ConfigParser()
    parser.read(origin)
    for k in parser['mysql']:
        if k in ('user', 'username', 'password'):
            v = parser['mysql'][k]
            parser['mysql'][k] = c.encrypt(v)

    with open(target, mode='w', encoding='utf8') as f:
        parser.write(f)

    with open(kp, mode='wb') as f:
        f.write(key)


if __name__ == '__main__':
    translate()
